import java.util.List;

import lib.Cell;

public class OthelloMinimax {
	
	final static int MAX_DEPTH = 5;
	
	private class MinimaxReturn {
		Cell cell;
		int score;

		public MinimaxReturn(int score) {
			this.score = score;
		}
	}

	private MinimaxReturn minimax(OthelloBoard board, Player playerMax, int maxDepth, int currentDepth) {
		
		final List<Cell> moves = board.getMoves();
		if (moves.isEmpty() || currentDepth == maxDepth) {
			return new MinimaxReturn(board.getDeltaPoints(playerMax));
		}
		
		MinimaxReturn best = new MinimaxReturn(0);
		best.score = board.getCurrentPlayer().equals(playerMax) ? Integer.MIN_VALUE : Integer.MAX_VALUE;
		
		for (Cell cellMove : moves) {
			OthelloBoard newBoard = board.makeMoveAndClone(cellMove);
			MinimaxReturn current = minimax(newBoard, playerMax, maxDepth, currentDepth+1);
			
			if (board.getCurrentPlayer().equals(playerMax)) {
				if (current.score > best.score) {
					best.score = current.score;
					best.cell = cellMove;
				}
			} else {
				if (current.score < best.score) {
					best.score = current.score;
					best.cell = cellMove;
				}
			}
		}
		
		return best;
	}
	
	public static Cell getBestMove(OthelloBoard board, Player player) {
		final Cell cell = new OthelloMinimax().minimax(board.clone(), player, MAX_DEPTH, 0).cell;
		return cell;
	}
	
}